package com.rankeiot.core.data;

import com.fasterxml.jackson.annotation.JsonIgnore;


import com.rankeiot.core.Current;
import com.rankeiot.core.data.response.Resp;
import com.rankeiot.core.dict.DataScope;
import com.rankeiot.core.exception.BusinessException;
import com.rankeiot.core.sqltoy.ScopeExecutor;
import lombok.Data;

import java.io.Serializable;
import java.util.*;

@Data
public class UserInfo implements Serializable {
    //token
    String token;
    //用户ID
    String id;
    //用户名
    String username;
    //用户姓名/昵称
    String name;
    //密码，已经过md5混淆,用于验证自动续期的token
    @JsonIgnore
    String password;
    /**
     *  用户类型 U:user,M:member
     *  其他类型用任意一位字符表示
     */
    char userType=Current.TYPE_USER;
    /**
     * 自定义的登录类型
     */
    char subType=Current.SUB_TYPE_DEFAULT;
    //机构ID
    String branchId;
    //所属机构编码
    String branchSn;
    String branchName;
    //头像
    String avatar;
    //性别
    String gender;
    Set<String> roles;
    //是否超级用户
    @JsonIgnore
    boolean isSuper;
    Set<String> permissions=new HashSet<>();
    //权限范围
    @JsonIgnore
    Map<String,String> scopes=new HashMap<>();

    List<MenuItem> menu=new ArrayList<>();

    Map<String,Object> props;

    public String getScopeSql(String userField,String branchField,String roleFiled){
        return ScopeExecutor.getScope(this, userField, branchField, roleFiled);
    }
    public boolean hasRole(String role){
        return roles.contains(role);
    }
    public boolean hasPermission(String permission){
        return permissions.contains(permission);
    }
    /*
    * 检测是否有权限，没有权限则跑出异常
     */
    public void assertBranch(String branchSn, String message) throws BusinessException {
        if (!hasPrivateOfBranch(branchSn)) {
            Resp.fail(message);
        }
    }
    /**
     * 是否具有该机构权限
     * @param branchSn 机构编码
     * @return
     */
    public boolean hasPrivateOfBranch(String branchSn){
        String userBranchSn=getBranchSn();
        for (Map.Entry<String, String> e : getScopes().entrySet()) {
            String sc = e.getValue();
            String roleCode = e.getKey();
            //含有全部权限，不需要判断
            if (DataScope.ALL.equals(sc)) {
                return true;
            }
            if (DataScope.DEPT.equals(sc)) {
               if(userBranchSn.equals(branchSn)){
                   return true;
               }
            } else if (DataScope.DEPT_AND_CHILD.equals(sc)) {
                if(branchSn.startsWith(userBranchSn)){
                    return true;
                }
            }
        }
        return false;
    }
}
